package org.dut.community.service;

import org.apache.commons.lang3.StringUtils;
import org.dut.community.dao.LoginTicketMapper;
import org.dut.community.dao.UserMapper;
import org.dut.community.entity.LoginTicket;
import org.dut.community.entity.User;
import org.dut.community.util.CommunityConstant;
import org.dut.community.util.CommunityUtil;
import org.dut.community.util.MailClient;
import org.dut.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.MailSender;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService implements CommunityConstant {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TemplateEngine templateEngine;
    @Value("${Community.path.domain}")
    private String domain; // 主域名
    @Value("${server.servlet.context-path}")
    private String contextPath; // 项目名
    @Autowired
    private MailClient mailClient;
    @Autowired
    private RedisTemplate redisTemplate;
//    @Autowired
//    private LoginTicketMapper loginTicketMapper;

    // 更新用户头像
    public int updateHeader(int userId,String headerUrl) {
        int rows = userMapper.updateHeader(userId,headerUrl);
        clearCache(userId);
        return rows;
    }

    // 登录
    public Map<String,String> login(String username,String password,int expiredSeconds){
        Map<String,String> map = new HashMap<>();
        // 空值处理
        if(StringUtils.isBlank(username)){
            map.put("usernameMsg","账号不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password)){
            map.put("passwordMsg","密码不能为空！");
            return map;
        }
        // 合法性校验
        User user = userMapper.selectByName(username);
        if(user == null){
            map.put("usernameMsg","该账号不存在！");
            return map;
        }
        if(user.getStatus() == 0){
            map.put("usernameMsg","账号未激活！");
            return map;
        }
        // 校验密码
        password = CommunityUtil.md5(password + user.getSalt());
        if(!user.getPassword().equals(password)){
            map.put("passwordMsg","密码错误！");
            return map;
        }
        // 登录成功
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.getUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000L));
//        loginTicketMapper.insertLoginTicket(loginTicket);
        // 存入redis
        redisTemplate.opsForValue().set(RedisKeyUtil.getTicketKey(loginTicket.getTicket()),loginTicket);

        map.put("ticket",loginTicket.getTicket());
        return map;
    }

    // 登出
    public void logout(String ticket){
        // 设置登录凭证为无效的
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
        loginTicket.setStatus(1);
        redisTemplate.opsForValue().set(redisKey,loginTicket);
    }

    // 加载主页帖子用户信息
    public User findUserById(int id){
        User user = getCache(id);
        if(user == null){
            user = initCache(id);
        }
        return user;
    }

    // 注册
    // map的key：表示属性名，value：表示错误提示
    public Map<String,Object> register(User user){
        Map<String,Object> map = new HashMap<>();
        if(user == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg","账号不能为空！");
            return map;
        }
        if(user.getPassword().length() < 8){
            map.put("passwordMsg","密码长度不得少于8位！");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg","邮箱不能为空！");
            return map;
        }
        // 账号重复
        User u = userMapper.selectByName(user.getUsername());
        if(u != null){
            map.put("usernameMsg","该账号已存在！");
            return map;
        }
        // 邮箱重复
        u = userMapper.selectByEmail(user.getEmail());
        if(u != null){
            map.put("emailMsg","该邮箱已被注册！");
            return map;
        }
        // 注册用户
        user.setSalt(CommunityUtil.getUUID().substring(0,5));
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));
        user.setType(0);
        user.setStatus(0);
        user.setActivationCode(CommunityUtil.getUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png",new Random().nextInt(1000)));
        user.setCreateTime(new Date());
        userMapper.insertUser(user);

        // 发送激活邮件
        Context context = new Context();
        context.setVariable("username",user.getUsername());
        context.setVariable("email",user.getEmail());
        // 激活链接：http://{domain}/{contextPath}/activation/{userid}/{activation_code}
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url",url);
        String content = templateEngine.process("/mail/activation",context);
        mailClient.sendMail(user.getEmail(),user.getUsername() + " 激活账号",content);
        return map;
    }

    // 激活账号
    public int activation(int userId,String code){
        User user = userMapper.selectById(userId);
        if(user == null){
            return ACTIVATION_FAILURE;
        }
        if(user.getStatus() == 1){
            return ACTIVATION_REPEAT;
        }
        if(!user.getActivationCode().equals(code)){
            return ACTIVATION_FAILURE;
        }
        userMapper.updateStatus(userId,1);
        clearCache(userId);
        return ACTIVATION_SUCCESS;
    }

    // 根据ticket查询登录凭证
    public LoginTicket getLoginTicket(String ticket){
        String redisKey = RedisKeyUtil.getTicketKey(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(redisKey);
    }

    // 更改密码
    public Map<String, Object> updatePassword(int userId, String oldPassword, String newPassword1, String newPassword2){
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.selectById(userId);
        String password = CommunityUtil.md5(oldPassword + user.getSalt());

        if (StringUtils.isBlank(oldPassword)) {
            map.put("oldPasswordMsg", "原密码不能为空！");
            return map;
        }
        if (!password.equals(user.getPassword())) {
            map.put("oldPasswordMsg", "原密码不正确！");
            return map;
        }
        if (StringUtils.isBlank(newPassword1) || StringUtils.isBlank(newPassword2)) {
            map.put("newPasswordMsg", "新密码不能为空！");
            return map;
        }
        if(newPassword1.length() < 8 || newPassword2.length() < 8){
            map.put("newPasswordMsg", "新密码长度不得少于8位！");
            return map;
        }
        if(!newPassword1.equals(newPassword2)){
            map.put("newPasswordMsg", "两次密码不一致！");
            return map;
        }

        userMapper.updatePassword(userId, CommunityUtil.md5(newPassword1+ user.getSalt()));
        return map;
    }

    // 重置密码--忘记密码
    public Map<String,String> resetPassword(String email,String password){
        Map<String,String> map = new HashMap<>();
        if(StringUtils.isBlank(email)){
            map.put("emailMsg","邮箱不能为空！");
            return map;
        }
        if(StringUtils.isBlank(password) || password.length() < 8){
            map.put("passwordMsg","密码为空 或 长度少于8位！");
            return map;
        }
        User user = userMapper.selectByEmail(email);
        if(user == null){
            map.put("emailMsg","邮箱不存在！");
            return map;
        }
        password = CommunityUtil.md5(password + user.getSalt());
        userMapper.updatePassword(user.getId(),password);
        return map;
    }

    // 重置密码--邮箱验证码
    public Map<String,String> getForgetCode(String email){
        Map<String,String> map = new HashMap<>();
        if(StringUtils.isBlank(email)){
            map.put("emailMsg","邮箱不能为空！");
            return map;
        }
        User user = userMapper.selectByEmail(email);
        if(user == null){
            map.put("emailMsg","邮箱不存在！");
            return map;
        }
        if(user.getStatus() == 0){
            map.put("emailMsg","账号未激活！");
            return map;
        }
        // 检查redis中是否存在该邮箱的验证码
        String redisKey = RedisKeyUtil.getForgetKey(email);
        if(redisTemplate.opsForValue().get(redisKey) != null){
            map.put("emailMsg","1分钟内只能获取一次验证码！");
            return map;
        }
        // 发送验证码
        String code = CommunityUtil.getUUID().substring(0,5);
        // 存入redis，设置有效时间60s
//        String redisKey = RedisKeyUtil.getForgetKey(email);
        redisTemplate.opsForValue().set(redisKey,code,60, TimeUnit.SECONDS);

        Context context = new Context();
        context.setVariable("username",user.getUsername());
        context.setVariable("code",code);
        //
        String content = templateEngine.process("/mail/forget",context);
        mailClient.sendMail(user.getEmail(),user.getUsername() + " 重置密码",content);
        map.put("verifyCode",code);
        return map;
    }

    public User findUserByName(String toName) {
        return userMapper.selectByName(toName);
    }

    // 获取用户权限
    public Collection<? extends GrantedAuthority> getAuthorities(int userId) {
        User user = findUserById(userId);
        List<GrantedAuthority> list = new ArrayList<>();
        list.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return switch (user.getType()) {
                    case 1 -> AUTHORITY_ADMIN;
                    case 2 -> AUTHORITY_MODERATOR;
                    default -> AUTHORITY_USER;
                };
            }
        });
        return list;
    }

    // 1.优先从redis取用户
    private User getCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(redisKey);
    }

    // 2.redis取不到，从mysql取
    private User initCache(int userId){
        User user = userMapper.selectById(userId);
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(redisKey, user, 3600, TimeUnit.SECONDS);
        return user;
    }

    // 3.数据变更时缓存清除
    private void clearCache(int userId){
        String redisKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(redisKey);
    }


}
